	package hydrap2p.controllercli;

import hydrap2p.helper.ServiceConnector;
import hydrap2p.modulemanager.ModuleManager;
import hydrap2p.modulemanager.ModuleInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.thrift.TException;

public class Controller {
	public static void main(String[] args)
	{
		new Controller().run();
	}
	private ModuleManager.Client manager;
	private List<ModuleInfo> programs;
	
	public Controller()
	{
		manager=ServiceConnector.getModuleManager();
	}
	
	public void run()
	{
		if (manager==null)
		{
			System.out.println("Could not contact module manager");
			return;
		}
		
		boolean running=true;
		BufferedReader inputreader=new BufferedReader(new InputStreamReader(System.in));
		while (running)
		{
			try {
				programs=manager.getModuleList();
			} catch (TException e) {
				System.out.println("Could not load modules list");
				return;
			}
			
			System.out.println("Pick a module to start or stop");
			for (int x=0; x<programs.size(); x++)
			{
				ModuleInfo current=programs.get(x);
				System.out.println(x+": "+current.name+"@"+current.server+" "+(current.running?"Running":"Stopped"));
			}
			System.out.println("X: Shutdown");
			
			String input="";
			try {
				input=inputreader.readLine();
			} catch (IOException e) {
				return;
			}
			
			System.out.println();
			
			if (input.toLowerCase().equals("x"))
			{
				try {
					manager.shutdown();
				} catch (TException e) {
				}
				return;
			}
			
			// parse numeric input
			int selection=0;
			try {
				selection=Integer.parseInt(input);
			}
			catch (Exception e){
				System.out.println("Could not parse your input");
				continue;
			}
			if (selection<0 || selection>=programs.size())
			{
				System.out.println("Could not parse your input");
				continue;
			}
			
			try {
				if (programs.get(selection).running)
					manager.stopModule(programs.get(selection).name, programs.get(selection).server);
				else
					manager.startModule(programs.get(selection).name, programs.get(selection).server);
			} catch (TException e) {
				System.out.println("Error while starting or stopping the program: "+programs.get(selection).name+"@"+programs.get(selection).server);
			}
			
		}
	}
}
